import router from '@/router'
// @ts-ignore
import nprogress from 'nprogress'
import { useUserStore } from './store/modules/user'
import pinia from './store'

const userStore = useUserStore(pinia)

// 配置进度条
nprogress.configure({
    easing: 'ease',
    speed: 500,
    showSpinner: false,
    trickleSpeed: 200,
    minimum: 0.3,
})

// 路由守卫
router.beforeEach(async (to, _, next) => {
    nprogress.start()

    // 定义 title
    document.title = to.meta.title as string

    let isLogin = userStore.token
    let username = userStore.username

    // 已经登陆的用户，不可以在访问登录页
    if (to.path === '/login' && isLogin) {
        next({ path: '/' })
        return
    }

    // 未登录的用户，不能访问非登录页
    if (!isLogin && to.path !== '/login') {
        next({ path: '/login', query: { redirect: to.path } })
        return
    }

    // 当没有用户信息 尝试获取用户信息
    if (isLogin && !username) {
        try {
            await userStore.userInfo()
            next({ ...to })
            return
        } catch {
            // 失败 说明token失效
            await userStore.userLogout()
            next({ path: '/login', query: { redirect: to.path } })
            return
        }
    }

    next()
})

router.afterEach((_to, _from) => {
    nprogress.done()
})
